# coding=utf-8

from app.cores.logger import DispatcherLogger
from app.cores.variable import Variable

import sys
from flask import session


class Script:

    def __init__(self, tool, dispatcher_logger, project_id=None):
        """
        初始化脚本工具对象
        :param tool: 工具
        :type tool: Tool
        :param dispatcher_logger: 日志
        :type dispatcher_logger: DispatcherLogger
        :param project_id: 工具所在项目id
        :type project_id: int
        """
        self.script_tool = tool.specific_tool
        self.dispatcher_logger = dispatcher_logger
        if project_id is None:
            self.project_id = session.get('project_id')
        else:
            self.project_id = project_id

    def exec_tool(self):
        error_msg = ''
        self.dispatcher_logger.logger.info('[脚本][执行]')
        if self.project_id is None:
            self.dispatcher_logger.logger.warn('[脚本]获取项目编号project_id为None, 不再执行该脚本')
        else:
            vars = Variable.get_project_variable(project_id=self.project_id)
            glb = {}
            loc = {}
            glb['vars'] = vars
            glb['log'] = self.dispatcher_logger.logger
            try:
                exec(self.script_tool.script_, glb, loc)
            except Exception as e:
                tb = sys.exc_info()[-1]
                while tb.tb_next:
                    tb = tb.tb_next
                error_msg = '\n脚本执行异常, 行号: %s, 错误信息: %s' % (tb.tb_lineno, e.args[0])
        log_text = self.dispatcher_logger.get_string_buffer()
        log_text += error_msg
        return log_text
